﻿using UnityEngine;
using UnityEngine.UI;
using System.Collections;

public class ChangeStage : MonoBehaviour {

    public Camera platformCamera;
    public Image img;
    private Sprite fadePic;

    public void changeStage()
    {
        RenderTexture tmp = new RenderTexture(platformCamera.pixelWidth, platformCamera.pixelHeight, 0);
        platformCamera.targetTexture = tmp;
        platformCamera.Render();
        int width = tmp.width;
        int height = tmp.height;
        Texture2D tex2d = new Texture2D(width, height, TextureFormat.ARGB32, false);
        RenderTexture.active = tmp;
        tex2d.ReadPixels(new Rect(0, 0, width, height), 0, 0);
        tex2d.Apply();
        fadePic = Sprite.Create(tex2d, new Rect(0, 0, width, height), Vector2.zero);
        img.sprite = fadePic;
        img.color = new Color(img.color.r, img.color.g, img.color.b, 1);
        StartCoroutine(stageFadeIn());
    }

    IEnumerator stageFadeIn()
    {
        while (img.color.a > 0)
        {
            img.color = new Color(img.color.r, img.color.g, img.color.b, img.color.a - 0.05f);
            yield return new WaitForEndOfFrame();
        }
        platformCamera.targetTexture = null;
    }

    IEnumerator stageFadeOut()
    {
        yield return new WaitForEndOfFrame();
    }
}
